import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,asyncRouters,constantRoutes,anyRouters } from '@/router'
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    //用户路由
    routes:[],
    //用户身份
    roles:[],
    //路由对比
    resultRoutes:[],
    //所有路由（包括常量路由）
    allRoutes:[],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
    
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  GETUSERINFO(state,userInfo){
    state.routes=userInfo.routes
    state.roles=userInfo.roles
    
  },
  SET_RESULTASYNCROUTES(state,resultroute){
    console.log(resultroute)
     state.resultRoutes=resultroute
     state.allRoutes= constantRoutes.concat(state.resultRoutes,anyRouters) 
      router.addRoutes(state.resultRoutes,state.anyRouters)
      router.options.routes = state.allRoutes
    }
  }

const computedAsyncRoutes = (asyncRouter,routes)=>{
  //过滤出当前用户【超级管理|普通员工】需要展示的异步路由
 return asyncRouter.filter(item=>{
      //数组当中没有这个元素返回索引值-1，如果有这个元素返回的索引值一定不是-1 
     if(routes.indexOf(item.name)!=-1){
       //递归:别忘记还有2、3、4、5、6级路由
       if(item.children&&item.children.length){
           item.children = computedAsyncRoutes(item.children,routes);
       }
       return true;
     }
  })
}


const actions = {
  // user login
 async login({ commit }, userInfo) {
    const { username, password } = userInfo
    let result=await login({ username: username.trim(), password: password })
    console.log(result)
    if(result.code===20000){
      commit('SET_TOKEN',result.data.token)
      setToken(result.data.token)
      return 'ok'
    }else{
      Promise.reject(new Error('登录失败'))
    }
    // return new Promise((resolve, reject) => {
    //   login({ username: username.trim(), password: password }).then(response => {
    //     const { data } = response
    //     commit('SET_TOKEN', data.token)
    //     setToken(data.token)
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
       const { name, avatar } = data
       console.log(data)
        commit('GETUSERINFO',data)  
        commit('SET_RESULTASYNCROUTES',computedAsyncRoutes(cloneDeep(asyncRouters),data.routes));
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}



export default {
  namespaced: true,
  state,
  mutations,
  actions,
  
}

